const Service = require('egg').Service;
const fs = require('fs');
const consola = require('consola');

class FilesService extends Service {

  // 文件上传
  async upFile(originFileObject, destFilePath) {
    return new Promise(resolve => {
      let readStream = fs.createReadStream(originFileObject.filepath);
      let writeStream = fs.createWriteStream(destFilePath);
      readStream.pipe(writeStream);

      writeStream.on('finish', () => {
        resolve(true);
      });
    });
  }

  // 文件删除
  async delFile(destFilePath) {
    return new Promise(resolve => {
      fs.unlink(destFilePath, (err: any) => {
        if (err !== null) {
          consola.error(new Error(err));
          resolve(false);
        }
        resolve(true);
      });
    });
  }
}

export default FilesService;
